package tech.cyhk.cloud.demo.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author swd
 * @date 2025/1/23
 */
@Slf4j
@Component
public class RtGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String pathVal = exchange.getRequest().getPath().value();

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        Mono<Void> filter = chain.filter(exchange);

        return filter.doFinally(signalType -> {
            stopWatch.stop();
            log.info("path={} rt={} signalType={}", pathVal, stopWatch.getTotalTimeMillis(), signalType);
        });
    }
}
